package com.chaodev.base.utils;

import com.chaodev.base.model.ElementTreeModel;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 树形工具类
 * @author zb
 */
public class TreeHelper {
    /**
     * 获取树形结构
     * @param elementTreeModelList 树形列表
     * @return
     */
    public static List<ElementTreeModel> getElementTreeInfo(List<ElementTreeModel> elementTreeModelList){
        if(elementTreeModelList.isEmpty()){
            return null;
        }
        //获取根节点
        return elementTreeModelList.stream().filter(m->"0".equals(m.getParentId()))
                .peek((m)-> m.setChildren(getChildrenList(m,elementTreeModelList).size()>0?getChildrenList(m,elementTreeModelList):null)).collect(Collectors.toList());
    }
    private static List<ElementTreeModel> getChildrenList(ElementTreeModel root, List<ElementTreeModel> all){
        return all.stream().filter(m-> m.getParentId().equals(root.getId())).peek((m)-> m.setChildren(getChildrenList(m,all).size()>0?getChildrenList(m,all):null)).collect(Collectors.toList());
    }
}
